<?php

/**
 * This is the model class for table "{{count_goods}}".
 *
 * The followings are the available columns in table '{{count_goods}}':
 * @property string $CountID
 * @property string $GoodsID
 * @property string $Year
 * @property integer $Month
 * @property integer $Day
 * @property string $ProductID
 * @property string $AdminID
 * @property string $CatID
 * @property string $ModuleID
 * @property string $StartTime
 * @property string $EndTime
 * @property string $Pprice
 * @property string $View
 * @property string $UserView
 * @property string $TouristView
 * @property string $Deal
 * @property string $MmjDeal
 * @property string $UDeal
 * @property string $Sales
 * @property string $AddTime
 */
class CountGoodsModel extends BaseModel
{

    public static $db;   
    public function getDbConnection(){
        if(self::$db!==null){
            return self::$db;
        }else{
            self::$db=Yii::app()->getComponent('db_count');
            if(self::$db instanceof CDbConnection)
                return self::$db;
            else
                throw new CDbException('连接出错');                    
        }            
    }
    //数据保存前操作
    protected function beforeSave() {
        //是否新增
        if ($this->isNewRecord) {
            $this->AddTime = time();
        } 
        return true;
    }

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{count_goods}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('CountID, GoodsID, Year, Month, Day, ProductID, AdminID, CatID, ModuleID, StartTime, EndTime, Pprice, View, UserView, TouristView, Deal, MmjDeal, UDeal, Sales, AddTime, RecordTime', 'safe'),
		);
	}

	/**
	 * @return array relational rules.
	 */
    public function relations() {
        return array(
            'GoodsModel' => array(self::BELONGS_TO, 'GoodsModel', 'GoodsID'),
        );
    }

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'CountID' => '统计ID',
			'GoodsID' => '商品主键ID',
			'Year' => '年',
			'Month' => '月',
			'Day' => '日',
			'ProductID' => '商品ID',
			'AdminID' => '后台人员ID',
			'CatID' => '分类ID',
			'ModuleID' => '模块ID',
			'StartTime' => '上架时间',
			'EndTime' => '下架时间',
			'Pprice' => '原价',
			'View' => '点击量',
			'UserView' => '用户点击量',
			'TouristView' => '游客点击旱',
			'Deal' => '成交量',
			'MmjDeal' => '妈咪街成交量',
			'UDeal' => 'U站成交量',
			'Sales' => '成效额(成交数*每单金额)',
			'AddTime' => '记录添加时间',
			'PromoPrice' => '折扣价',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;









		$criteria->compare('CountID',$this->CountID,true);
		$criteria->compare('GoodsID',$this->GoodsID,true);
		$criteria->compare('Year',$this->Year,true);
		$criteria->compare('Month',$this->Month);
		$criteria->compare('Day',$this->Day);
		$criteria->compare('ProductID',$this->ProductID,true);
		$criteria->compare('AdminID',$this->AdminID,true);
		$criteria->compare('CatID',$this->CatID,true);
		$criteria->compare('ModuleID',$this->ModuleID,true);
		$criteria->compare('Pprice',$this->Pprice,true);
		$criteria->compare('View',$this->View,true);
		$criteria->compare('UserView',$this->UserView,true);
		$criteria->compare('TouristView',$this->TouristView,true);
		$criteria->compare('Deal',$this->Deal,true);
		$criteria->compare('MmjDeal',$this->MmjDeal,true);
		$criteria->compare('UDeal',$this->UDeal,true);
		$criteria->compare('Sales',$this->Sales,true);
		$criteria->compare('AddTime',$this->AddTime,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	public function createSearchCriteria()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;



		if(!empty($_GET['count_start_time'])){
			$count_start_time = strtotime($_GET['count_start_time']);
			$criteria->addCondition('RecordTime >= ' . $count_start_time);
		}
		if(!empty($_GET['count_end_time'])){
			$count_end_time = strtotime($_GET['count_end_time']) + 86400;
			$criteria->addCondition('RecordTime < ' . $count_end_time);
		}




		if(!empty($_GET['add_start_time'])){
			$add_start_time = strtotime($_GET['add_start_time']);
			$criteria->addCondition('AddTime >= ' . $add_start_time);
		}
		if(!empty($_GET['add_end_time'])){
			$add_end_time = strtotime($_GET['add_end_time']) + 86400;
			$criteria->addCondition('AddTime < ' . $add_end_time);
		}


		if(is_numeric($this->StartTime)){
			$criteria->compare('StartTime',$this->StartTime,true);
		}else{
			if(!empty($this->StartTime)){
				$StartTime = strtotime($this->StartTime);
				$criteria->addCondition('StartTime >= ' . $StartTime);	
			}		
		}

		if(is_numeric($this->EndTime)){
			$criteria->compare('EndTime',$this->EndTime);
		}else{
			if(!empty($this->EndTime)){
				$EndTime = strtotime($this->EndTime) + 86400;
				$criteria->addCondition('EndTime <= ' . $EndTime);
			}			
		}






		$criteria->compare('t.CountID',$this->CountID,true);
		$criteria->compare('t.GoodsID',$this->GoodsID,true);
		$criteria->compare('t.Year',$this->Year,true);
		$criteria->compare('t.Month',$this->Month);
		$criteria->compare('t.Day',$this->Day);
		$criteria->compare('t.ProductID',$this->ProductID);
		$criteria->compare('t.AdminID',$this->AdminID,true);
		$criteria->compare('t.CatID',$this->CatID,true);
		$criteria->compare('t.ModuleID',$this->ModuleID,true);
		$criteria->compare('t.Pprice',$this->Pprice,true);
		$criteria->compare('t.View',$this->View,true);
		$criteria->compare('t.UserView',$this->UserView,true);
		$criteria->compare('t.TouristView',$this->TouristView,true);
		$criteria->compare('t.Deal',$this->Deal,true);
		$criteria->compare('t.MmjDeal',$this->MmjDeal,true);
		$criteria->compare('t.UDeal',$this->UDeal,true);
		$criteria->compare('t.Sales',$this->Sales,true);
		$criteria->compare('t.AddTime',$this->AddTime,true);

		return 	$criteria;	
	}


	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return CountGoodsModel the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}


    /**
     * 执行所选时间范围的统计，可能是某一天，可能是隔几天的分析，
     * 分析的时候是一天一天的时间去分析的
     * @param type $start_time 开始时间
     * @param type $end_time 结束时间
     * 每张GuestDataModel表表示每天的数据，给它做一下统计
     * @return boolean
     */
    public function sendFenxi($start_time = '', $end_time = '') {
        set_time_limit(400);
        if (empty($start_time)) {
            $start_time = strtotime(date('Y-m-d 00:00:00'));
        }
        if (empty($end_time)) {
            $end_time = strtotime(date('Y-m-d 23:59:59'));
        }

        //总共需要统计多少天的量
        $intCount = ($end_time - $start_time)%86400;
        for($i = 0; $i < $intCount; $i++){
            self::saveDataOneDate($start_time + $i*86400);
        }
    }



    /**
     * 通过一个时间戳或者时间然后判断是分析哪张表的数据，然后执行分析
     * @return [type] [description]
     */
    public static function saveDataOneDate($mixTime, $GoodsID = ''){
        if(is_numeric($mixTime)){
            //时间戳格式
        }else{
            //时间格式
            $mixTime = strtotime($mixTime);
        }
        //这个时间的年月日，
        $intYear = date('Y', $mixTime);
        $intMonth = date('m', $mixTime);
        $intDay = date('d', $mixTime);

        $strTime = date('Ymd', $mixTime);
        GuestDataModel::$strTableName = '{{guest_data'.$strTime.'}}';

        //这个时间的这一天的开始时间  与结束时间
        $intCStart = strtotime($intYear.'-'.$intMonth.'-'.$intDay);
        $intCEnd = $intCStart + 86400;
        //算出这一天在上架的商品
        $objModel = new GoodsModel();
        $arrWhere = array(
            'StartTime' => array('sign' => '<', 'data' => $intCEnd),
            'EndTime' => array('sign' => '>=', 'data' => $intCStart),   
            'order' => 'GoodsID asc',      
        );
        if($GoodsID){
        	$arrWhere['GoodsID'] = array('sign' => '>', 'data' => $GoodsID);
        }
        $objCriteria = BaseModel::getC($arrWhere);
        $objCriteria->limit = 50;
        //这一天在上架的商品
        $objDatas = $objModel->findAll($objCriteria);


        foreach($objDatas as $objData){
            //获取这商品这一天，总查看数，会员查看数，游客查看数
            $arrW = array('Year' => $intYear, 'Month' => $intMonth, 'Day' => $intDay);            
        	$arrW['GoodsID'] = $objData->GoodsID;
        	$View = GuestDataModel::model()->count(BaseModel::getC($arrW));
        	$arrW['UserID'] = array('sign' => '>', 'data' => 0);
        	$UserView = GuestDataModel::model()->count(BaseModel::getC($arrW));
        	$TouristView = $View - $UserView;


        	$Deal = SalesDataModel::model()->getTurnover($objData->GoodsID, $intCStart, $intCEnd);//成交量
        	$MmjDeal = SalesDataModel::model()->getTurnoverGuan($objData->GoodsID, $intCStart, $intCEnd);//妈咪街成交量
        	$UDeal = $Deal - $MmjDeal;//U站成交量

            $arrData = array(
                'GoodsID' => $objData->GoodsID,
                'Year' => $intYear,
                'Month' => $intMonth,
                'Day' => $intDay,
                'ProductID' => $objData->ProductID,
                'AdminID' => $objData->AdminID,
                'CatID' => $objData->CatID,
                //'ModuleID' => $objData->ModuleID,
                'StartTime' => $objData->StartTime,
                'EndTime' => $objData->EndTime,
                'Pprice' => $objData->Pprice,
                'PromoPrice' => $objData->PromoPrice,
                'View' => $View,
                'UserView' => $UserView,
                'TouristView' => $TouristView,
                'Deal' => $Deal,
                'MmjDeal' => $MmjDeal,
                'UDeal' => $UDeal,
                'Sales' => $Deal * $objData->PromoPrice,
                'RecordTime' => $intCStart,
            );

        	$objModel = self::model()->find(BaseModel::getC(array('GoodsID' => $objData->GoodsID, 'Year' => $arrData['Year'], 'Month' => $arrData['Month'], 'Day' => $arrData['Day'])));
        	if(!$objModel){
        		$objModel = new CountGoodsModel();
        	}
        	$objModel->attributes = $arrData;
        	$objModel->save(false);
        	echo "商品主键ID：{$objData->GoodsID},{$arrData['Month']}月{$arrData['Day']}销售点击情况分析完成</br>";
        }        
        return empty($objModel->GoodsID) ?  0 :  $objModel->GoodsID;   
    }
}
